﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using MugenMvvmToolkit.Attributes;
using MugenMvvmToolkit.Interfaces.ViewModels;

namespace MugenMvvmToolkit.Infrastructure
{
    /// <summary>
    ///     Represents the class that provide display name of object.
    /// </summary>
    public class AnnotationDisplayNameProvider : DisplayNameProvider
    {
        #region Overrides of DisplayNameProvider

        /// <summary>
        ///     Gets a display name for the specified type using the specified member.
        /// </summary>
        /// <param name="memberInfo">The specified member.</param>
        /// <returns>
        ///     An instance of string.
        /// </returns>
        protected override string GetDisplayNameInternal(MemberInfo memberInfo)
        {
            DisplayNameAttribute nameAttribute =
                memberInfo.GetCustomAttributes(typeof(DisplayNameAttribute), true)
                          .OfType<DisplayNameAttribute>()
                          .FirstOrDefault();

            if (nameAttribute != null)
                return nameAttribute.DisplayName;

#if !NOANNOTATIONVALIDATION
            DisplayAttribute displayAttribute =
                memberInfo.GetCustomAttributes(typeof(DisplayAttribute), true)
                          .OfType<DisplayAttribute>()
                          .FirstOrDefault();
            if (displayAttribute != null)
                return displayAttribute.GetName();
#endif

#if NETFX_CORE
            var type = memberInfo as TypeInfo;
            if (type != null && typeof(IViewModel).IsAssignableFrom(type.AsType()))
                return string.Empty;
#else
            var type = memberInfo as Type;
            if (type != null && typeof(IViewModel).IsAssignableFrom(type))
                return string.Empty;
#endif
            return memberInfo.Name;
        }

        #endregion
    }
}